//计算金额
function calculate() {
	var checks = document.getElementsByName("check"); //每一个单选按钮
	var onePriceS = document.getElementsByClassName("jiage"); //每个商品的单价
	var onenumS = document.getElementsByClassName("num"); //每个商品的数量
	var price = 0.00;
	for (var i = 0; i < checks.length; i++) {
		if (checks[i].checked) {
			//单个数量
			var oneNum = Number(onenumS[i].value);
			//单个价值
			var onePri = Number(onePriceS[i].innerText);
			//计算每个的价值
			price += oneNum * onePri;
		}
	}
	document.getElementById("total").innerText = price;
}
//全选并计算金额
function check(a) {
	var checks = document.getElementsByName("check"); //每一个单选按钮
	for (var i = 0; i < checks.length; i++) {
		checks[i].checked = a.checked;
	}
	calculate();
}
//加一个
function jia(b) {
	var result = b.previousElementSibling;//上一个数量元素
	result.value=Number(result.value)+1;
	calculate();
}
//剪一个
function jian(c) {
	var result = c.nextElementSibling;
	if(Number(result.value)>0){
		result.value=Number(result.value)-1;
	}
	calculate();
}

//移除
function del(d){
	var elements = d.parentElement.parentElement;
	elements.remove();
	calculate();
}

//添加
function add(e){
	//商品名字
	var goodsName = e.parentElement.firstElementChild.firstElementChild.innerHTML;
	//商品价格
	var goodsPrice =e.parentElement.firstElementChild.lastElementChild.innerHTML;
	//商品图片
	var goodsImg =e.previousElementSibling.src;
	//代码
	var goods ='<tr>'+
				'<th><input type="checkbox" name="check" onclick="calculate()"></th>'+
				'<td>'+goodsName+'</td>'+
				'<td><img src="'+goodsImg+'" width="100"></td>'+
				'<td class="jiage">'+goodsPrice+'</td>'+
				'<td>'+
					'<input type="button" class="left" value="-" onclick="jian(this)">'+
					'<input type="text" class="num" value="0" onchange="calculate()">'+
					'<input type="button" class="right" value="+" onclick="jia(this)">'+
				'</td>'+
				'<td><input type="button" value="移除" onclick="del(this)"></td>'+
			'</tr>';
	
	var trAll =document.getElementById("tb").children;//全部的tr
	var isNo =true;//判断是否有该元素
	for(var i=0; i<trAll.length;i++){
		if(trAll[i].firstElementChild.nextElementSibling.innerHTML==goodsName){
			return;
		}
	}
	if(isNo){
		document.getElementById("tb").innerHTML+=goods;
	}
}
